<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>WebSocket 测试页面</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 20px;
    }
    .container {
      max-width: 800px;
      margin: 0 auto;
    }
    .input-group {
      margin-bottom: 20px;
    }
    input, button {
      padding: 8px;
      margin-right: 10px;
    }
    #log {
      border: 1px solid #ccc;
      padding: 10px;
      height: 300px;
      overflow-y: auto;
      white-space: pre-wrap;
    }
  </style>
</head>
<body>
<div class="container">
  <div class="input-group">
    <input type="text" id="wsUrl" placeholder="输入 WebSocket 地址" value="ws://localhost:8083/push/ws/json/1">
    <button onclick="connectWebSocket()">连接</button>
    <button onclick="disconnectWebSocket()">断开连接</button>
  </div>
  <div class="input-group">
    <input type="text" id="messageInput" placeholder="输入要发送的消息">
    <button onclick="sendMessage()">发送</button>
  </div>
  <div id="log"></div>
</div>

<script>
  let ws;

  function connectWebSocket() {
    const url = document.getElementById('wsUrl').value;
    try {
      ws = new WebSocket(url);

      ws.onopen = function() {
        logMessage('连接成功');
      };

      ws.onmessage = function(event) {
        logMessage(`收到消息: ${event.data}`);
      };

      ws.onclose = function(event) {
        if (event.wasClean) {
          logMessage(`连接关闭，代码: ${event.code}, 原因: ${event.reason}`);
        } else {
          logMessage('连接意外断开');
        }
      };

      ws.onerror = function(error) {
        logMessage(`发生错误: ${error.message}`);
      };
    } catch (error) {
      logMessage(`连接失败: ${error.message}`);
    }
  }

  function disconnectWebSocket() {
    if (ws && ws.readyState === WebSocket.OPEN) {
      ws.close();
    }
  }

  function sendMessage() {
    const message = document.getElementById('messageInput').value;
    if (ws && ws.readyState === WebSocket.OPEN && message) {
      ws.send(message);
      logMessage(`发送消息: ${message}`);
      document.getElementById('messageInput').value = '';
    } else {
      logMessage('请先连接到 WebSocket 服务器或输入消息');
    }
  }

  function logMessage(message) {
    const logElement = document.getElementById('log');
    const timestamp = new Date().toLocaleTimeString();
    logElement.innerHTML += `[${timestamp}] ${message}\n`;
    logElement.scrollTop = logElement.scrollHeight;
  }
</script>
</body>
</html>
